package com.lh.java.basic.threadlocal;

import java.util.Random;

public class TreadLocalDemo implements Runnable{
	private final static ThreadLocal<Student> studentLocal = new ThreadLocal<Student>();

	public static void main(String[] agrs) {
		TreadLocalDemo td = new TreadLocalDemo();
		Thread t1 = new Thread(td, "a");
		Thread t2 = new Thread(td, "b");
		Thread t3 = new Thread(td, "c");
		Thread t4 = new Thread(td, "d");
		Thread t5 = new Thread(td, "e");
		Thread t6 = new Thread(td, "f");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
	
	}

	public void run() {
		accessStudent();
	}

	public void accessStudent() {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(currentThreadName + " is running!");
		Random random = new Random();
		int age = random.nextInt(100);
		System.out
				.println("thread " + currentThreadName + " set age to:" + age);
		Student student = getStudent();
		student.setAge(age);
		System.out.println("thread " + currentThreadName
				+ " first read age is:" + student.getAge());
		try {
			Thread.sleep(100);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		remove();
//		setStudent(null);
		student =null;
		System.gc();
		try {
			Thread.sleep(500);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		System.out
		.println("thread " + currentThreadName +" clean over");
//		student = getStudent();
//		System.out.println("thread " + currentThreadName
//				+ " second read age is:" + student.getAge());
	}

	public Student getStudent() {
		Student student = (Student) studentLocal.get();
		if (student == null) {
			student = new Student();
			setStudent(student);
		}
		return student;
	}

	public void setStudent(Student student) {
		studentLocal.set(student);
	}
	public void remove() {
		studentLocal.remove();
	}
	
}
